package cn.jh.smartos.service;

import android.content.Intent;
import android.provider.Telephony;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.jh.smartos.App;
import cn.jh.smartos.bean.ConnConfig;
import cn.jh.smartos.client.ClientService;
import cn.jh.smartos.utils.NetWorkKit;

/**
 * Created by pjh on 18/3/12.
 */

public class SimpleHttpServer {

    public static final String NEW_CLIENT = "new_client";
    public static final String SERVICE_STATE = "service_state";
    public static final String SERVICE_EXCEPTION = "service_exception";
    private String TAG = "SimpleHttpServer";
    private WebConfiguration webConfig;
    private Set<IResourceUrlHandler> resourceHandlers;
    private boolean isEnable;
    private static ServerSocket socket;
    private final ExecutorService threadPool;
    //    private List<InetAddress> inetAddressList;


    public SimpleHttpServer(WebConfiguration webConfig) {
        this.webConfig = webConfig;

//        inetAddressList =new  ArrayList();
        threadPool = Executors.newCachedThreadPool();
        resourceHandlers = new HashSet<IResourceUrlHandler>();


    }

    public static ServerSocket getSocket() {
        return socket;

    }

    /**
     * 开启服务
     */
    public void startAsync() {
        Log.e(TAG, "startAsync");
        isEnable = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                doProcSync();

            }
        }).start();

    }


    /**
     * 停止服务
     *
     * @throws IOException
     */
    public void stopAsync() throws IOException {

        if (!isEnable) {
            return;
        }

        isEnable = false;
        socket.close();
        socket = null;
        Intent intent = new Intent(SERVICE_STATE);
        intent.putExtra(SERVICE_STATE, false);
        mLocalBroadcastManager.sendBroadcast(intent);

    }

    private LocalBroadcastManager mLocalBroadcastManager = LocalBroadcastManager.getInstance(App.Companion.getContext());

    private void doProcSync() {

        InetSocketAddress socketAddr = new InetSocketAddress(webConfig.getProt());

        try {
            socket = new ServerSocket();
            socket.bind(socketAddr);
            Intent intent = new Intent(SERVICE_STATE);
            intent.putExtra("port", webConfig.getProt());
            intent.putExtra(SERVICE_STATE, true);
            mLocalBroadcastManager.sendBroadcast(intent);

            Log.e(TAG, "发送SERVICE_OPEN广播" + socket.getLocalSocketAddress());
            while (isEnable) {

                final Socket remotepeer = socket.accept();
                SocketAddress socketAddress = remotepeer.getRemoteSocketAddress();
                socketService = new HearbeatSocketService(remotepeer);
                Intent ins = new Intent(NEW_CLIENT);
                ins.putExtra(NEW_CLIENT, socketAddress.toString());
                mLocalBroadcastManager.sendBroadcast(ins);
                socketService.inits();

            }
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
            Intent intent = new Intent(SERVICE_EXCEPTION);
            intent.putExtra(SERVICE_EXCEPTION, e.getMessage());
            mLocalBroadcastManager.sendBroadcast(intent);

        }
    }

    private static HearbeatSocketService socketService = null;

    public static HearbeatSocketService getSocketService() {
        return socketService;
    }

    public void registerResourceHandler(IResourceUrlHandler handler) {
        resourceHandlers.add(handler);

    }

    /**
     * 处理远端socket
     *
     * @param remotePeer 远端socket
     */
    private void onAcceptRemotePeer(Socket remotePeer) {

        try {
     /*       HttpContext httpContext = new HttpContext();
            httpContext.setUnderlySocket(remotePeer);*/
            OutputStream outputStream = remotePeer.getOutputStream();
            OutputStreamWriter we = new OutputStreamWriter(outputStream);
            we.write("congratulation, connected successful   1");
            we.write("congratulation, connected successful   2");
            we.write("congratulation, connected successful   3");
            we.write("congratulation, connected successful   4");
            we.flush();
            InputStream nis = remotePeer.getInputStream();
            InputStreamReader nisRea = new InputStreamReader(nis);
            Log.e(TAG, nisRea.toString());

          /*  String headLine=null;
            String resourceUrl=headLine=StreamToolKit.readLine(nis).split(" ")[1];
            Log.e("spy++++++++++",resourceUrl);


            while ((headLine = StreamToolKit.readLine(nis))!=null){
                if(headLine.equals("\r\n")){
                    break;
                }
                String[] pair=headLine.split(": ");
                if (pair.length>1){
                    httpContext.addRequestHeader(pair[0],pair[1]);
                }

                Log.e("spy",headLine);
            }
            for (IResourceUrlHandler handler:resourceHandlers){
                if (!handler.accept(resourceUrl)){
                    continue;
                }
                handler.handle(resourceUrl,httpContext);
            }*/
        } catch (IOException e) {
            Log.e(TAG, e.toString());
        }

    }
}
